import Vue from 'vue'
import axios from 'axios'
import {
  removeToken,
  getToken
} from '@/utils';
const API_SUCCESS_CODE = '0';
let baseURL = process.env.BASE_API;
if (process.env.NODE_ENV === 'development') {
  baseURL = 'http://127.0.0.1:9000/common'; // 测试
}
// 创建axios实例
const service = axios.create({
  baseURL,
  timeout: 60000, // 请求超时时间
  withCredentials: true
})

// request拦截器
service.interceptors.request.use(config => {
  config.headers.Authorization = getToken();
  if (config.showLoading) {
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(response => {
  const res = response.data;
  if (res === null) {
    return res
  }
  if (res.code === API_SUCCESS_CODE && !res.data) {
    res.data = 1;
  }
  if (res.code !== API_SUCCESS_CODE) {
    res.data = null;
  }
  // token 过期
  if (res.code === 'A100003') {
    removeToken();
    window.location.href = window.location.origin + '/login';
  } else if (res.code === 'SYS_ERROR_500') {
    // 参数校验不通过
    res.msg && Vue.prototype.$message.error(res.msg)
    return res;
  } else if (response && response.headers && response.headers['accept-ranges'] && response.headers['accept-ranges'] === 'bytes') {
    return response;
  } else if (res.code && res.code !== '0') {
    res.msg && Vue.prototype.$message.error(res.msg);
    return res;
  } else {
    return res;
  }
}, error => {
  removeToken();
  const res = error.response.data;
  const status = error.response.status;
  if (status === 403) {
    window.parent.postMessage({
      type: 'Event',
      name: 'Event_refreshToken',
      data: {
        token: ''
      }
    })
  }
  res.msg && Vue.prototype.$message.error(res.msg);
  Promise.reject(error)
})
export default service
